package com.atguigu.Mytest;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class AirCondition{
    private int number = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void jia() throws InterruptedException {
        lock.lock();
        try {
            while (number !=0){
                condition.await();
            }
            System.out.println(Thread.currentThread().getName()+"\t"+(++number));
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public void jian() throws InterruptedException {
        lock.lock();
        try {
            while(number==0){
                condition.await();
            }
            System.out.println(Thread.currentThread().getName()+"\t"+(--number));
            condition.signalAll();
        } finally {
            lock.unlock();
        }


    }

}






public class ProdConsumerDemo {
    public static void main(String[] args) {
        AirCondition airCondition = new AirCondition();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(200);
                    airCondition.jia();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(300);
                    airCondition.jian();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(400);
                    airCondition.jia();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(500);
                    airCondition.jian();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();

    }
}
